package com.youbug.mall.member_ums.service.impl;

import cn.hutool.json.JSONObject;
import com.youbug.common.to.SocialUserTo;
import com.youbug.common.util.HttpUtils;
import com.youbug.mall.member_ums.entity.UmsMember;
import com.youbug.mall.member_ums.entity.UmsMemberLevel;
import com.youbug.mall.member_ums.exception.PhoneException;
import com.youbug.mall.member_ums.exception.UsernameException;
import com.youbug.mall.member_ums.mapper.UmsMemberMapper;
import com.youbug.mall.member_ums.service.IUmsMemberLevelService;
import com.youbug.mall.member_ums.service.IUmsMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.mall.member_ums.utils.MyBCryptPasswordEncoder;
import com.youbug.mall.member_ums.vo.MemberUserLoginVo;
import com.youbug.mall.member_ums.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import com.youbug.common.vo.QueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2024-06-17
 */
@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements IUmsMemberService {

    @Autowired
    private IUmsMemberLevelService memberLevelService;

        @Override
        public IPage<UmsMember> getUmsMemberPage(QueryVo<UmsMember> queryVo) {

        Page<UmsMember> paramPage = new Page<>();

        paramPage.setCurrent(queryVo.getCurrentPage());

        paramPage.setSize(queryVo.getPageSize());

        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();

        UmsMember umsMember = queryVo.getPayload();

        if(!ObjectUtils.isEmpty(umsMember)){
            if(umsMember.getId()!=null){
            wrapper.gt("id", umsMember.getId());
            }
            if(umsMember.getLevelId()!=null){
            wrapper.gt("level_id", umsMember.getLevelId());
            }
            if(StringUtils.hasText(umsMember.getUsername())){
                wrapper.eq("username", umsMember.getUsername());
            }
            if(StringUtils.hasText(umsMember.getPassword())){
                wrapper.eq("password", umsMember.getPassword());
            }
            if(StringUtils.hasText(umsMember.getNickname())){
                wrapper.eq("nickname", umsMember.getNickname());
            }
            if(StringUtils.hasText(umsMember.getMobile())){
                wrapper.eq("mobile", umsMember.getMobile());
            }
            if(StringUtils.hasText(umsMember.getEmail())){
                wrapper.eq("email", umsMember.getEmail());
            }
            if(StringUtils.hasText(umsMember.getHeader())){
                wrapper.eq("header", umsMember.getHeader());
            }
                    if(umsMember.getGender()!=null){
                    wrapper.gt("gender", umsMember.getGender());
                    }
            if(StringUtils.hasText(umsMember.getCity())){
                wrapper.eq("city", umsMember.getCity());
            }
            if(StringUtils.hasText(umsMember.getJob())){
                wrapper.eq("job", umsMember.getJob());
            }
            if(StringUtils.hasText(umsMember.getSign())){
                wrapper.eq("sign", umsMember.getSign());
            }
                    if(umsMember.getSourceType()!=null){
                    wrapper.gt("source_type", umsMember.getSourceType());
                    }
                    if(umsMember.getIntegration()!=null){
                    wrapper.gt("integration", umsMember.getIntegration());
                    }
                    if(umsMember.getGrowth()!=null){
                    wrapper.gt("growth", umsMember.getGrowth());
                    }
                    if(umsMember.getStatus()!=null){
                    wrapper.gt("status", umsMember.getStatus());
                    }
        }
        if(!ObjectUtils.isEmpty(queryVo.getStartTime())){
            wrapper.gt("create_time", queryVo.getStartTime());
        }
        if(!ObjectUtils.isEmpty(queryVo.getEndTime())){
            wrapper.lt("create_time", queryVo.getEndTime());
        }
        wrapper.orderByDesc("create_time");

        Page<UmsMember> page = this.page(paramPage, wrapper);

        return page;
        }

    /* @Transactional(transactionManager = "transactionManagerXXX", rollbackFor = Exception.class)
     public boolean saveBatch(Collection<UmsMember> entityList) {
     return saveBatch(entityList, DEFAULT_BATCH_SIZE);
     }
     */

    @Override
    @Transactional(transactionManager = "transactionManagerUms", rollbackFor = Exception.class)
    public void register(UserRegisterVo vo) {

        UmsMember member = new UmsMember();
        //设置默认等级
        UmsMemberLevel levelEntity = memberLevelService.getDefaultLevel();
        member.setLevelId(levelEntity.getId());

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        member.setNickname(vo.getUserName());
        member.setUsername(vo.getUserName());
        //密码进行MD5加密
        MyBCryptPasswordEncoder bCryptPasswordEncoder = new MyBCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        member.setPassword(encode);
        member.setMobile(vo.getPhone());
        member.setGender(0);
        member.setCreateTime(new Date());

        this.save(member);
    }

    public void checkPhoneUnique(String phone) throws PhoneException {

        Integer phoneCount = this.count(new QueryWrapper<UmsMember>().eq("mobile", phone));

        if (phoneCount > 0) {
            throw new PhoneException();
        }
    }

    public void checkUserNameUnique(String userName) throws UsernameException {

        Integer usernameCount = this.count(new QueryWrapper<UmsMember>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public UmsMember login(MemberUserLoginVo vo) {


        return null;
    }

    @Override
    public UmsMember login(SocialUserTo socialUser) throws Exception {
        //具有登录和注册逻辑
        String uid =null;
        Map<String,String> query = new HashMap<>();
        query.put("access_token",socialUser.getAccess_token());
//            query.put("uid",socialUser.getUid());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
        JSONObject userInfoJson = null;
        if (response.getStatusLine().getStatusCode() == 200) {
            //查询成功
            String json = EntityUtils.toString(response.getEntity());
            userInfoJson = new JSONObject(json);
            uid = userInfoJson.get("id", String.class);
        }
        if(uid==null){
            throw new RuntimeException("未获取到gitee用户id");
        }
        //1、判断当前社交用户是否已经登录过系统
        UmsMember member = getOne(new QueryWrapper<UmsMember>().eq("social_uid", uid));

        if (member != null) {
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            UmsMember update = new UmsMember();
            update.setId(member.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            updateById(update);

            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());
            return member;
        } else {
               //2、没有查到当前社交用户对应的记录我们就需要注册一个
                UmsMember register = new UmsMember();
                String name = userInfoJson.get("name", String.class);
                String gender = userInfoJson.get("gender", String.class);
                String profileImageUrl = userInfoJson.get("avatar_url", String.class);

                register.setNickname(name);
                register.setGender("m".equals(gender)?1:0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(uid);
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(socialUser.getExpires_in());
                //把用户信息插入到数据库中
                save(register);

                return register;
        }
    }

}
